<?php

namespace app\index\model;

use app\common\library\BLiveTools;
use app\common\model\Room as RoomModel;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Paginator;

/**
 * 渔场模型
 * Class Room
 * @package app\index\model
 */
class Room extends RoomModel
{
    /**
     * 获取全部记录
     * @param array $param
     * @param bool $isCache
     * @return Room[]|array|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAll(array $param = [], $isCache = false)
    {
        // 额外补充房间信息
//        $this->extraQuery($param);
        // 检索查询条件
        $filter = $this->getFilter($param);
        // 查询列表数据
        return $this->where($filter)->cache($isCache, 60, 'tetrList')->order(['update_time' => 'desc', 'tetris_status' => 'desc', 'room_id'])->select();
    }

    /**
     * 获取列表
     * @param array $param
     * @return Paginator
     * @throws DbException
     */
    public function getList(array $param = []): Paginator
    {
        // 检索查询调价你
        $filter = $this->getFilter($param);
        // 查询列表数据
        return $this->where($filter)
            ->order(['tetris_status' => 'desc', 'room_id', 'update_time'])
            ->paginate([
                'query'     => request()->param(), // url额外参数
                'list_rows' => request()->param('limit', 15), //每页数量
            ]);
    }

    /**
     * 检索查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param = []): array
    {
        // 默认查询条件
        $params = $this->setQueryDefaultValue($param, [
            'search'      => '', // 关键词检索
            'online'      => -1, // 是否在玩
            'live_status' => -1, // 是否开播
            'type'        => 'all', // 搜索类型
        ]);

        // 检索查询条件
        $filter = [];

        // 有关键词时强制查询全部状态
        if (!empty($params['search'])) {

            // 根据搜索类型匹配字段
            $allowFields = ['uname', 'title', 'room_id', 'area_name', 'medal_name'];
            if (in_array($params['type'], $allowFields)) {
                $fields = $params['type'] === 'area_name' ? 'area_name|parent_area_name' : $params['type'];
            } else {
                $fields = 'uname|title|room_id|area_name|parent_area_name|medal_name';
            }

            $filter[] = [$fields, 'like', "%{$params['search']}%"];
        }

        // 没有关键词时查询指定状态
        $params['online'] > -1 && $filter[] = ['tetris_status', '=', $params['online']];
        $params['live_status'] > -1 && $filter[] = ['live_status', '=', $params['live_status']];
        return $filter;
    }

    /**
     * 补充采集逻辑
     * @param $params
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function extraQuery($params)
    {
        // 存在搜索关键词并且是数字时
        if (!empty($params['search'])) {
            $room = trim($params['search']);
            if (preg_match('/^\d+$/', $room)) {
                $model = new self;
                if (!$model->where('room_id', '=', $room)->find()) {
                    // 没有该房间则进行额外采集逻辑
                    $tools = new BLiveTools([]);
                    $anchor = $tools->ApiGetAnchorInRoom($room);
                    if ($anchor) {
                        $gameInfo = $tools->ApiGetRoomGameInfo($room);
                        if ($gameInfo && array_key_exists('1659261256750', $gameInfo)) {
                            // 查询开播状态
                            $liveInfo = $tools->ApiGetRoomPlayInfo($room);
                            $liveStatus = $liveInfo && array_key_exists('live_status', $liveInfo) ? $liveInfo['live_status'] : 0;
                            $this->save([
                                'room_id'     => $room,
                                'anchor_name' => $anchor['uname'],
                                'room_title'  => '',
                                'cover_url'   => '',
                                'avatar_url'  => $anchor['face'],
                                'online'      => 1,
                                'last_scan'   => time(),
                                'live_status' => $liveStatus,
                            ]);
                        }
                    }
                }
            }
        }
    }
}
